package xin.petstore.framework.orm.mybatis.paginator.jackson2;

import xin.petstore.framework.orm.mybatis.paginator.domain.PageList;
import xin.petstore.framework.orm.mybatis.paginator.domain.Paginator;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class PageListJsonSerializer extends JsonSerializer<PageList> {
    ObjectMapper mapper;

    public PageListJsonSerializer() {
        this.mapper = new ObjectMapper();
    }

    public PageListJsonSerializer(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void serialize(PageList value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        Map map = new HashMap();
        Paginator paginator = value.getPaginator();
        map.put("totalCount", Integer.valueOf(paginator.getTotalCount()));
        map.put("totalPages", Integer.valueOf(paginator.getTotalPages()));
        map.put("page", Integer.valueOf(paginator.getPage()));
        map.put("limit", Integer.valueOf(paginator.getLimit()));
        map.put("items", new ArrayList(value));

        map.put("startRow", Integer.valueOf(paginator.getStartRow()));
        map.put("endRow", Integer.valueOf(paginator.getEndRow()));

        map.put("offset", Integer.valueOf(paginator.getOffset()));

        map.put("slider", paginator.getSlider());

        map.put("prePage", Integer.valueOf(paginator.getPrePage()));
        map.put("nextPage", Integer.valueOf(paginator.getNextPage()));

        map.put("firstPage", Boolean.valueOf(paginator.isFirstPage()));
        map.put("hasNextPage", Boolean.valueOf(paginator.isHasNextPage()));
        map.put("hasPrePage", Boolean.valueOf(paginator.isHasPrePage()));
        map.put("lastPage", Boolean.valueOf(paginator.isLastPage()));

        this.mapper.writeValue(jgen, map);
    }
}